const fs = require("fs");
const path = require("path");
const http = require("http");
const os = require("os");

const txtPath = path.resolve(__dirname, "../dist/1.txt");

if (!fs.existsSync(txtPath)) {
  const file = fs.createWriteStream(txtPath);
  for (let i = 0; i <= 1e6; i++) {
    file.write("Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n");
  }
  file.end();
  file.close();
  console.log("end");
}

const server = http.createServer(function (req, res) {
  const url = req.url;

  switch (url) {
    case "/": {
      let str = fs.readFileSync(txtPath);
      res.write(str);
      res.end();
      break;
    }
    case "/stream": {
      const rs = fs.createReadStream(txtPath);
      rs.pipe(res);
      break;
    }
    default: {
      res.writeHead(404);
      res.end();
    }
  }
});
server.listen(1234, "0.0.0.0", function () {
  console.log("http://127.0.0.1:1234");
  console.log("http://127.0.0.1:1234/stream");
  // 定时查看内存
  setInterval(() => {
    console.clear();
    console.log(os.totalmem() / 1024 / 1024 + "MB", os.freemem() / 1024 / 1024 + "MB", process.memoryUsage());
  }, 1000);
});
